package dk.ahp.getmeoff;

import org.osmdroid.api.IGeoPoint;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;
import org.osmdroid.views.overlay.MyLocationOverlay;
import org.osmdroid.views.overlay.PathOverlay;

import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;

/**
 * Creates a org.osmdroid.views.MapView and centers on current location, or between start and destinatin. 
 */
public class DestMapActivity extends AbstractActivity {
	private static final String TAG = DestMapActivity.class.getSimpleName();
    private MapController mapController;
    private MapView mapView;
    private MyLocationOverlay myLocationOverlay;
    private long downTime;
    int titleId = -1;
    AlertDialog dlg = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dest_map);
        
        mapView = (MapView) findViewById(R.id.mapview);
		mapView.setClickable(true);
		mapView.setEnabled(true);
        mapView.setMultiTouchControls(true);
        mapView.setBuiltInZoomControls(true);
        mapController = mapView.getController();
        mapController.setZoom(13);
        
        myLocationOverlay = new MyLocationOverlay(this, mapView);
        myLocationOverlay.enableMyLocation();
        mapView.getOverlays().add(myLocationOverlay);
        
        if (null != GetMeOffApplication.getMeOffApplication.tmpDestination.getDestination()) {
        	Location dest = GetMeOffApplication.getMeOffApplication.tmpDestination.getDestination();
        	Location start = GetMeOffApplication.getMeOffApplication.tmpDestination.getStart();
        	GeoPoint destPt = new GeoPoint(dest.getLatitude(), dest.getLongitude());
        	if (null != start && 0!=start.getLatitude() && 0 !=start.getLongitude() && 0!=dest.getLatitude() && 0!=dest.getLongitude()) {
        		 GeoPoint startPt = new GeoPoint(start.getLatitude(), start.getLongitude());
        	     PathOverlay myPath = new PathOverlay(Color.RED, this);
        	     Paint paint = myPath.getPaint();
        	     paint.setStrokeWidth(5);
        	     myPath.addPoint(startPt);
        	     myPath.addPoint(destPt);
        	     mapView.getOverlays().add(myPath);
        	     double latDif = Math.abs(dest.getLatitude() - start.getLatitude());
        	     double lonDif = Math.abs(dest.getLongitude() - start.getLongitude());
        	     double centerLat = Math.min(dest.getLatitude(), start.getLatitude()) + latDif/2;
        	     double centerLon = Math.min(dest.getLongitude(), start.getLongitude()) + lonDif/2;
        	     GeoPoint center = new GeoPoint(centerLat, centerLon);
        	     mapController.setCenter(center); // sæt kortet midt mellem start og bestemmelses sted.
        	}
        	else {
        		mapController.setCenter(destPt);
        	}
        }
        else {
        	Location loc = GetMeOffApplication.getMeOffApplication.currentLocation;
        	if (null == loc) {
        		loc = GetMeOffApplication.getMeOffApplication.bestGuessLocation;
        		Log.d(TAG, "loc best guess");
        	}
        	if (null != loc) {
        		Log.d(TAG, "Set center to " + loc);
        		GeoPoint currentPoint = new GeoPoint(loc.getLatitude(), loc.getLongitude());  
        		mapController.setCenter(currentPoint);
        	} else {
        		mapController.setZoom(13);
        		GeoPoint currentPoint = new GeoPoint(55.71997, 12.44049);
        		mapController.setCenter(currentPoint);
        	}
        }
        Intent i = getIntent();
        Bundle b = i.getExtras();
        if (null != b) {
        	titleId = b.getInt("name");
        	setTitle(getResources().getString(titleId));
        }
        Log.d(TAG, "onCreate done");
    }

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
	    int actionType = ev.getAction();
	    switch (actionType) {
	    case MotionEvent.ACTION_UP:
	    	long now = System.currentTimeMillis();
	    	long timeDiff = now - downTime;
	    	if( timeDiff < 250 ) {// det kan være et tab
	    		downTime = 0;
	    		Projection proj = mapView.getProjection();
	    		IGeoPoint loc = proj.fromPixels((int)ev.getX(), (int)ev.getY());
	    		final Location tmpLoc = new Location("");
	    		tmpLoc.setLatitude(((double)loc.getLatitudeE6())/1000000);
	    		tmpLoc.setLongitude(((double)loc.getLongitudeE6())/1000000);
	    		
	    		String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
	    		String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);

	    		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
	    		dialog.setTitle(getResources().getString(R.string.save_position));
	    		dialog.setMessage(longitude + " " + latitude);
	    		UpdateDialog ud = new UpdateDialog();
				ud.execute(loc.getLongitudeE6(), loc.getLatitudeE6());

				dialog.setPositiveButton(getResources().getString(R.string.yes), new AlertDialog.OnClickListener() {
	    			public void onClick(DialogInterface arg0, int arg1) {
	    				if (titleId ==  R.string.title_activity_dist_map) {
	    					Log.d(TAG, "Saves destiantion");
	    					GetMeOffApplication.getMeOffApplication.tmpDestination.setDestination(tmpLoc);
	    				}
	    				else if (titleId == R.string.title_activity_dist_map_start) {
	    					Log.d(TAG, "Saves start position");
	    					GetMeOffApplication.getMeOffApplication.tmpDestination.setStart(tmpLoc);
	    				}
	    				finish();
	    			}
	    		});
	    		dialog.setNegativeButton(getResources().getString(R.string.no), null);
	    		dlg = dialog.create();
	    		dlg.show(); 
	    		//dialog.show();
	    	}
	    	break;
	    case MotionEvent.ACTION_DOWN:
	    	downTime = System.currentTimeMillis();
	    	break;
	    }
	    return super.dispatchTouchEvent(ev);
	}
	
	/**
	 * This class finds the address for a location in background and writes the address to the outer class'es dialog.
	 */
	class UpdateDialog extends AsyncTask<Integer, Void, String> {
		@Override
		protected String doInBackground(Integer... params) {
			Location tmpLoc = new Location("");
    		tmpLoc.setLongitude(((double)params[0])/1000000);
    		tmpLoc.setLatitude(((double)params[1])/1000000);
			String res = Destination.locationToAddres(tmpLoc, true);
			return res;
		}
		
		@Override
		protected void onPostExecute(String resultat) {
			if (null != dlg && null != resultat) {
				dlg.setMessage(resultat);
				dlg.show();
			}
		}
	}
}
